package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        log.info("手机号："+phone);
        //调用ValidateCodeUtils获取验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("验证码："+validateCode);
        //调用SMSUtils2,给该手机号发送相应的验证码短信
        //SMSUtils.sendMessage(phone,validateCode.toString());
        //将该验证码存入session域中,使用手机号作为key，值就是验证码
        //session.setAttribute(phone,validateCode);
        session.setAttribute("phone",phone);
        //session.setAttribute("code",validateCode.toString());
        redisTemplate.opsForValue().set("code",validateCode,5, TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map map, HttpSession session){
        String inputPhone = (String) map.get("phone");
        String inputCode = (String) map.get("code");
        //检查手机号码
        String correctPhone = (String) session.getAttribute("phone");
        if (!correctPhone.equals(inputPhone)){
            return R.error("手机号码错误,登录失败");
        }
        //核验验证码
        //String correctCode = (String) session.getAttribute("code");
        Object correctCode = redisTemplate.opsForValue().get("code");
        if (correctCode.equals(inputCode)){
            //比对成功检查是否为新用户
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,inputPhone);
            User user = userService.getOne(lqw);
            //新用户,添加到User表中
            if (user == null){
                User newUser = new User();
                newUser.setPhone(inputPhone);
                userService.save(newUser);
                session.setAttribute("userId",newUser.getId());
                return R.success(newUser);
            }else {
                //不是新用户，也将用户信息[id]存入到session中
                session.setAttribute("userId",user.getId());
                redisTemplate.delete("code");
                return R.success(user);
            }
        }
        return R.error("验证码错误，登录失败");
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(){
        return R.success("退出成功");
    }
}
